<?php

require 'simple_html_dom.php';
ini_set('max_execution_time', 999999999);
ini_set('max_input_time', 999999999);

function htmltrim($string){
	$string = trim($string);
	$pattern = '(?:[ \t\n\r\x0B\x00\x{A0}\x{AD}\x{2000}-\x{200F}\x{201F}\x{202F}\x{3000}\x{FEFF}]|&nbsp;|<br\s*\/?>)+';
	return preg_replace('/^' . $pattern . '|' . $pattern . '$/u', '', $string);
}

function getAttribute($string, $marker1, $marker2){
	$len1 = strlen($marker1);
	$len2 = strlen($marker2);
	//echo "string: $string, marker1: $marker1, marker2: $marker2, len1: $len1<br>";
	if($len1 == 0 && $len2 == 0){
		return "";
	}
	else if($len2 == 0){
		$pos1 = strpos($string, $marker1);
		if($pos1 === false){
			return "";
		}
		$pos1 = $pos1 + $len1;
		$pos2 = strlen($string);
	return htmltrim(substr($string, $pos1, $pos2 - $pos1));
	}
	else if($len1 == 0){
		$pos1 = 0;
		$pos2 = strpos($string, $marker2);
		if($pos2 === false){
			return "";
		}
	return htmltrim(substr($string, $pos1, $pos2 - $pos1));
	}
	
	$pos1 = strpos($string, $marker1);
	$pos2 = strpos($string, $marker2);
	if($pos1 === false && $pos2 === false){
		return "";
	}
	if($pos1 === false){
		$pos1 = 0;
	}
	else{
		$pos1 = $pos1 + $len1;
	}
	if($pos2 === false){
		$pos2 = strlen($string);
	}
	//echo "$pos1, $pos2<br>";
	return htmltrim(substr($string, $pos1, $pos2 - $pos1));
}

function getTeamName($abbr){
	$abbr = trim(strtolower($abbr));
	//echo "get abbr: $abbr<br>";
	$teamMap = array(
		"ari" => "Arizona Cardinals",
		"pho" => "Arizona Cardinals Phoenix Cardinals",
		"slc" => "Arizona Cardinals St. Louis Cardinals",
		"chc" => "Arizona Cardinals Chicago Cardinals",
		"chp" => "Arizona Cardinals Chicago/Pittsburgh",
		
		"atl" => "Atlanta Falcons",
		
		"bal" => "Baltimore Ravens",
		
		"buf" => "Buffalo Bills",
		
		"car" => "Carolina Panthers",
		
		"chi" => "Chicago Bears",
		"chs" => "Chicago Bears Chicago Stanleys",
		"dec" => "Chicago Bears Decatur Stanleys",
		
		"cin" => "Cincinnati Bengals",
		
		"cle" => "Cleveland Browns",
		
		"dal" => "Dallas Cowboys",
		
		"den" => "Denver Broncos",
		
		"det" => "Detroit Lions",
		"por" => "Detroit Lions Portsmouth Spartans",
		
		"gnb" => "Green Bay Packers",
		
		"hou" => "Houston Texans",
		
		"ind" => "Indiannapolis Colts",
		"blc" => "Indiannapolis Colts Baltimore Colts",
		
		"jac" => "Jacksonville Jaguars",
		
		"kan" => "Kansas City Chiefs",
		
		"mia" => "Miami Dolphins",
		
		"min" => "Minnesota Vikings",
		
		"nwe" => "New England Patriots",
		"bsp" => "New England Patriots Boston Patriots",
		
		"nor" => "New Orleans Saints",
		
		"nyg" => "New York Giants",
		
		"nyj" => "New York Jets",
		"nyt" => "New York Jets New York Titans",
		
		"oak" => "Oakland Raiders",
		"lad" => "Oakland Raiders Los Angeles Raiders",
		"okr" => "Oakland Raiders",
		
		"phi" => "Philadelphia Eagles",
		"php" => "Philadelphia Eagles Philadelphia/Pittsburgh",
		
		"pit" => "Pittsburgh Steelers",
		"pip" => "Pittsburgh Steelers Pittsburgh Pirates",
		
		"sdg" => "San Diego Chargers",
		"lac" => "San Diego Chargers Los Angeles Chargers",
		
		"sfo" => "San Francisco 49ers",
		
		"sea" => "Seattle Seahawks",

		"stl" => "St. Louis Rams",
		"lam" => "St. Louis Rams Los Angeles Rams",
		"clr" => "St. Louis Rams Cleveland Rams",
		
		"tam"=> "Tampa Bay Buccaneers",
		
		"ten" => "Tennessee Titans",
		"tno" => "Tennessee Titans Tennessee Oilers",
		"hoo" => "Tennessee Titans Houston Oilers",
		
		"was"=> "Washington Redskins",
		"bsr" => "Washington Redskins Boston Redskins",
		"bbr" => "Washington Redskins Boston Braves"
	);
	//echo "teamMap:<br>".var_dump($teamMap)."<br>";
	if(array_key_exists($abbr, $teamMap)){
		$team = $teamMap[$abbr];
	}
	else{
		$team = strtoupper($abbr);
	}
	//echo "$abbr: $team<br>";
	return $team;	
}

function getTeams($htmlRows){
	$teams = array();
	if($htmlRows == null){
		return "";
	}
	$teamCache = array();
	foreach($htmlRows as $row){
		$total = $row->find("[colspan=3]");
		if($total != null){
			break;
		}
		$team = $row->children(2)->plaintext;
		if(!in_array($team, $teamCache)){
			array_push($teamCache, $team);
			$team = getTeamName($team);
			if(!in_array($team, $teams)){
				array_push($teams, $team);
			}
		}		
	}
	return implode($teams, " ");
}

function getAwards($pid, $awardBio){
	if($awardBio == null){
		return;
	}
	$type = "pro";
	echo "Award ($pid) html: ".$awardBio->plaintext."<br>";
	$line = $awardBio->children(0);
	//echo "first line: ".var_dump($line)."<br>";
	$year = null;
	while($line != null){
		//echo "line: ".$line->plaintext."<br>";
		
		if($line->tag == "font"){
			$year = $line->plaintext;
		}
		if($line->tag == "a"){
			if($year == null){ //stupid ads
				break;
			}
			$title = $line->plaintext;
			if(preg_match("/heisman/i", $title) > 0){
				$type = 'college';
			}
			else {
				$type = 'pro';
			}
			$insert = "INSERT INTO AWARDS (award_title, player_id, year, type) VALUES('$title', $pid, $year, '$type')";
			//echo "<br>******<br>$insert<br>******<br><br>";
			mysql_query($insert);
			$id = mysql_insert_id();
			if($id == 0){
				echo "<span style='color:red;'>FAILED to INSERT Award</span><br>$insert<br>";
			}
			$year = null;
		}
		$line = $line->next_sibling();
	}	
}

function getPlayerInfo($href){
	//$href = "playerpage.htm?ilkid=ALLENMAR01";
	//$href = "playerpage.htm?ilkid=ARRINLAV01";
	$debug = false;
	$base_url = "http://databasefootball.com/players/";
	//echo "href: $href<br>";
	//echo "$base_url $href<br>";
	$p_url = $base_url.$href;
	//echo "player url: $p_url<br>";
	$player_page = file_get_html($p_url);
	$bio = $player_page->find('font.bio', 0);
	//echo var_dump($bio);
	$plaintext = $bio->plaintext;
	$innerText = $bio->innerText;
	//echo "innerText: $innerText<br>";
	echo "Plaintext: $plaintext<br>";
	$plaintext = preg_replace("(\'\')", "\"", $plaintext);
	$plaintext = preg_replace("(\')", "\'", $plaintext);
	$fullName = $position = $height = $weight = $dob = $hometown = $college = $drafted = $nickname= "null";
	$fullName = getAttribute($plaintext, "", "Position:");
	if(preg_match("/Full Name:/", $plaintext)){
		if(!(strpos($fullName, "Full Name:") === false)){
			$fullName = getAttribute($plaintext, "Full Name:", "Position:");
		}
	}
	if(preg_match("/\(*\)/", $fullName)){
		$nickname = getAttribute($plaintext, "(", ")");
	}
	//echo "FullName: $fullName<br>";
	if(preg_match("/Position:/", $plaintext)){
		if(preg_match("/Height:/", $plaintext)){
			$position = getAttribute($plaintext, "Position:", "Height:");
		}
		else{
			$position = getAttribute($plaintext, "Position:", "Born:");
		}
	}
	if(preg_match("/Height:/", $plaintext)){
		$height = getAttribute($plaintext, "Height:", "Weight:");
	}
	if(preg_match("/Weight:/", $plaintext)){
		$weight = getAttribute($plaintext, "Weight:", "Born:");
	}
	if(preg_match("/Born:/", $plaintext)){
		if(preg_match("/, in/", $plaintext)){
			$dob = getAttribute($plaintext, "Born:", ", in");
			$hometown = getAttribute($plaintext, ", in", "High School:");
		}
		else if(preg_match("/High School:/", $plaintext)){
			$dob = getAttribute($plaintext, "Born:", "High School:");
			$dob = preg_replace("/,/", "", $dob);
		}
		else{
			$dob = getAttribute($plaintext, "Born:", "");
		}
		$dob = preg_replace("/,/", "", $dob);
	}
	if(preg_match("/College:/", $plaintext)){
		$college = getAttribute($plaintext, "College:", "Drafted");
	}
	if(preg_match("/Drafted:/", $plaintext)){
		$drafted = getAttribute($plaintext, "Drafted:", "");
	}
	//$fullName = $player_page->find("a h1")->plaintext;
	$header = $player_page->find("a[name] h1", 0);
	$fullName = $header->plaintext;
	//Jerry Da prato
	//John Smith
	//La var Arrington
	$fullName = preg_replace("/[[:space:]]([A-Z])/", " !$1", htmltrim($fullName));
	$fullName = preg_replace("(\')", "\'", $fullName);
	//echo var_dump($fullName)."<br>";
	$name_array = explode(' !', $fullName);
	$first = $name_array[0];
	$last = $name_array[1];
	//echo "trs: ".var_dump($player_page->find('table tr[onmouseover]'));
	$teams = getTeams($player_page->find('table tbody tr td table tbody tr[onmouseover]'));
	//echo "Name: $fullName<br>";
	if($debug){
		echo "plaintext: $plaintext<br>";
		echo "nickName: $nickname<br>";
		echo "Position: '$position'<br>";
		echo "height: $height<br>";
		echo "weight: $weight<br>";
		echo "dob: $dob<br>";
		echo "hometown: $hometown<br>";
		echo "college: $college<br>";
		echo "drafted: $drafted<br>";
		echo "teams: $teams<br><br>";
	}
	$insert = "INSERT INTO players (
				first_name, last_name, height, weight, dob, position, team, college, hometown, drafted, nickname) 
				VALUES('$first', '$last', '$height', $weight, '$dob', '$position', '$teams', '$college', '$hometown', '$drafted', '$nickname')";
	preg_replace("/''/", "'", $insert);
	echo $insert."<br>";
	$result = mysql_query($insert);
	$id = mysql_insert_id();
	if($id == 0){
		echo "<span style='color:red;'>FAILED to INSERT Player</span><br>$plaintext<br>$insert<br>";
	}
	/***********************
	///awards section
	/***********************/
	getAwards($id, $player_page->find('td p font.bio', 0));
	
	$player_page->clear();
	unset($player_page);
}

$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
 
mysql_select_db("staging", $con);

$select_links = "Select link from unique_links";
$result = mysql_query($select_links);
while($link = mysql_fetch_assoc($result)){
	$link = 
	getPlayerInfo($link['link']);
}


?>